package com.qilu.pe.ui.activity;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectChangeListener;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.qilu.pe.R;
import com.qilu.pe.base.Base2Activity;
import com.qilu.pe.base.BaseResult2;
import com.qilu.pe.base.Config;
import com.qilu.pe.base.Global;
import com.qilu.pe.dao.bean.Income;
import com.qilu.pe.dao.http.APIRetrofit;
import com.ruitu.arad.api.RxUtil;
import com.ruitu.arad.base.base_list.ListBaseAdapter;
import com.ruitu.arad.base.base_list.SuperViewHolder;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

// 我的收入
public class MyIncomeActivity extends Base2Activity {
    private RecyclerView rcv_list;
    private TextView tv_start_time, tv_end_time;

    private IncomeListAdapter adapter;
    private List<Income> incomeList = new ArrayList<>();

    private String startDate;// 开始日期
    private String endDate;// 结束日期

    @Override
    protected int getLayoutRes() {
        return R.layout.activity_my_income;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        rcv_list = findViewById(R.id.rcv_list);
        tv_start_time = findViewById(R.id.tv_start_time);
        tv_end_time = findViewById(R.id.tv_end_time);

        setHeadTitle("我的收入");

        adapter = new IncomeListAdapter(this);
        LinearLayoutManager manager = new LinearLayoutManager(this);
        rcv_list.setLayoutManager(manager);
        rcv_list.setAdapter(adapter);

        setListeners();

        hideProgress();
        reqIncomeList();
        showProgress();
    }

    private void setListeners() {
        setOnClickListener(tv_start_time, tv_end_time);
        tv_start_time.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                startDate = tv_start_time.getText().toString().trim();
                if (!TextUtils.isEmpty(startDate) && !TextUtils.isEmpty(endDate)) {
                    hideProgress();
                    reqIncomeList();
                    showProgress();
                }
            }
        });
        tv_end_time.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                endDate = tv_end_time.getText().toString().trim();
                if (!TextUtils.isEmpty(startDate) && !TextUtils.isEmpty(endDate)) {
                    hideProgress();
                    reqIncomeList();
                    showProgress();
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        if (v == tv_start_time) {// 支付日期起
            dateType = 1;
            initDatePicker();
            pvTime.show();
        }
        if (v == tv_end_time) {// 支付日期结束
            dateType = 2;
            initDatePicker();
            pvTime.show();
        }
    }

    private TimePickerView pvTime;
    private int dateType = 1;// 日期选择器的类型 1 开始日期 2 结束日期

    private void initDatePicker() {//Dialog 模式下，在底部弹出
        pvTime = new TimePickerBuilder(this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                if (dateType == 1) {// 开始日期
                    startDate = getTime(date);
                    tv_start_time.setText(startDate);
                } else {// 结束日期
                    endDate = getTime(date);
                    tv_end_time.setText(endDate);
                }
            }
        }).setTimeSelectChangeListener(new OnTimeSelectChangeListener() {
            @Override
            public void onTimeSelectChanged(Date date) {
            }
        }).setType(new boolean[]{true, true, true, false, false, false})
                .isDialog(true) // 默认设置false ，内部实现将DecorView 作为它的父控件。
                .addOnCancelClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {

                    }
                })
                .setItemVisibleCount(7) //若设置偶数，实际值会加1（比如设置6，则最大可见条目为7）
                .setLineSpacingMultiplier(2.0f)
                .isAlphaGradient(true)
                .setTitleText("选择日期")
                .build();

        Dialog mDialog = pvTime.getDialog();
        if (mDialog != null) {
            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.BOTTOM);
            params.leftMargin = 0;
            params.rightMargin = 0;
            pvTime.getDialogContainerLayout().setLayoutParams(params);

            Window dialogWindow = mDialog.getWindow();
            if (dialogWindow != null) {
                dialogWindow.setWindowAnimations(com.bigkoo.pickerview.R.style.picker_view_slide_anim);//修改动画样式
                dialogWindow.setGravity(Gravity.BOTTOM);//改成Bottom,底部显示
                dialogWindow.setDimAmount(0.3f);
            }
        }
    }

    private String getTime(Date date) {//可根据需要自行截取数据显示
        if (dateType == 1) {// 开始日期
            SimpleDateFormat format = new SimpleDateFormat(Config.TIME_FORMATE_YMD);
            return format.format(date);
        } else {// 结束日期
            SimpleDateFormat format = new SimpleDateFormat(Config.TIME_FORMATE_YMD);
            return format.format(date);
        }
    }

    private Disposable reqIncomeList() {
        return APIRetrofit.getDefault().reqMyIncomeList(Global.HEADER, 1, 999999, startDate, endDate)
                .compose(RxUtil.<BaseResult2<List<Income>>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<List<Income>>>() {
                    @Override
                    public void accept(BaseResult2<List<Income>> listResult2) throws Exception {
                        hideProgress();
                        if (listResult2.isSuccess()) {

                        } else {

                        }
                        incomeList = listResult2.getData();
                        adapter.setDataList(incomeList);
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                    }
                });
    }

    private class IncomeListAdapter extends ListBaseAdapter<Income> {

        public IncomeListAdapter(Context context) {
            super(context);
        }

        @Override
        public int getLayoutId() {
            return R.layout.item_income_list;
        }

        @Override
        public void onBindItemHolder(SuperViewHolder holder, int position) {
            TextView tv_date = holder.getView(R.id.tv_date);
            TextView tv_test = holder.getView(R.id.tv_test);
            TextView tv_paid = holder.getView(R.id.tv_paid);
            TextView tv_back = holder.getView(R.id.tv_back);
            TextView tv_distribite = holder.getView(R.id.tv_distribite);
            LinearLayout ll_item = holder.getView(R.id.ll_item);

            Income income = mDataList.get(position);

            tv_date.setText(income.getCreated_at());
            tv_test.setText(income.getMoney());
            tv_paid.setText(income.getPrice());
            tv_back.setText(income.getPayment());
            tv_distribite.setText(income.getShare());

            if (position % 2 == 0) {
                ll_item.setBackgroundResource(R.color.white);
            } else {
                ll_item.setBackgroundResource(R.color.com_gray);
            }
        }
    }
}